package com.tbit.uqbike.client.controller.interceptor;


import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;

/**
 * @Author: chen
 * @Description:
 * @Date: 创建于 13:59 2019/12/30
 */
public class LanguageInterceptor implements HandlerInterceptor {
    public static final String DEFAULT_PARAM_NAME = "lang";
    private String paramName = DEFAULT_PARAM_NAME;

    /**
     * 说明：1、springMVC四种方式
     * 1.1、cookie 方式（不考虑）
     * 1.2、session 集群方式失效
     * 1.3、acceptHeader 请求头方式
     * 1.4、fixed  固定方式(采用这种方式，只拦截登录接口，设置语言)
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String newLocale = request.getHeader(getParamName());

        LocaleResolver localeResolver = RequestContextUtils.getLocaleResolver(request);
        if (localeResolver == null) {
            throw new IllegalStateException(
                    "No LocaleResolver found: not in a DispatcherServlet request?");
        }
        localeResolver.setLocale(request, response, parseLocaleValue(newLocale));
        /**获取时区，存放内存*/
        String timeZone = request.getHeader("timeZone");
        /**时区默认东八区*/
        if (timeZone == null) {
            timeZone = "GMT+08:00";
        }
        if (request.getSession().getAttribute("timeZone") == null) {
            request.getSession().setAttribute("timeZone", timeZone);
        }
        return true;

    }

    private Locale parseLocaleValue(String lang) {
        //默认语言是中文
        if (StringUtils.isBlank(lang)) {
            Locale locale = new Locale("zh", "CN");
            return locale;
        }
        Locale locale = new Locale("zh", "CN");
        if (lang.equalsIgnoreCase("en")) {
            locale = new Locale("en", "US");
        } else if (lang.equalsIgnoreCase("cn")) {
            locale = new Locale("zh", "CN");
        } else if (lang.equalsIgnoreCase("th")) {
            locale = new Locale("th", "TH");
        }
        return locale;
    }

    public String getParamName() {
        return paramName;
    }

    public void setParamName(String paramName) {
        this.paramName = paramName;
    }
}
